#include<vector>
#include<algorithm>
#include<queue>
using namespace std;

class Solution {
public:
    int maxEvents(vector<vector<int>>& events) {
        if (events.size() < 2) return events.size();
        sort(events.begin(), events.end(), [](const vector<int>& left, const vector<int>& right) {
            return left[0] < right[0];
            });

        int cnt = 0;
        int cur = 0;
        int index = 0;
        priority_queue<int, vector<int>, greater<int>>queue;
        while (index < events.size() || !queue.empty()) {
            while (!queue.empty() && queue.top() < cur)
                queue.pop();
            while (true) {
                while (index < events.size() && events[index][0] <= cur) {
                    if (events[index][1] >= cur)
                        queue.emplace(events[index][1]);
                    ++index;
                }
                if (index >= events.size() || !queue.empty())
                    break;
                cur = events[index][0];
            }
            if (!queue.empty()) {
                queue.pop();
                ++cnt;
            }
            ++cur;
        }
        return cnt;
    }
};
